﻿// ==UserScript==
// @name				Popup Search
// @author				lkytal
// @namespace			Lkytal
// @homepage			http://coldfire.qiniudn.com/
// @description			Popup Search Box and translate Button (etc) for selected Text
// @include				*
// @require				http://code.jquery.com/jquery-2.1.1.min.js
// @version				2.6.3
// @icon				http://lkytal.qiniudn.com/ic.ico
// @grant				GM_xmlhttpRequest
// @grant				GM_addStyle
// @grant				unsafeWindow
// @grant				GM_openInTab
// @grant				GM_setClipboard
// @grant				GM_getClipboard
// @grant				GM_getValue
// @grant				GM_setValue
// @grant				GM_registerMenuCommand
// @homepageURL			https://greasyfork.org/scripts/340-popup-search
// ==/UserScript==
// Generated by CoffeeScript 1.7.1


if (window != window.top || window.document.title === "")
	return;
var GetOpt, InTextBox, Init, Inter, Load, MouseIn, OpenSet, SetOpt, SettingWin, ShowBar, TimeOutHide, bTrans, baiduico, bingicon, fixPos, getLastRange, get_offsets_and_remove, get_selection_offsets, gicon, ie, pending, ticon, tip, tipdown, tipup, txt;

tipdown = "";

tipup = "";

tip = tipdown;

baiduico = "";

bingicon = "";

ticon = "";

gicon = "";

ie = "";

pending = "";

txt = "";

InTextBox = function(selection) {
  $('textarea, input[type=text], *[contenteditable="true"]', document).each(function(i) {
    if (selection.containsNode(this, true)) {
      return true;
    }
  });
  return false;
};

getLastRange = function(selection) {
  var lastRange, r, _i, _ref;
  lastRange = selection.getRangeAt(selection.rangeCount - 1);
  for (r = _i = _ref = selection.rangeCount - 1; _ref <= 0 ? _i <= 0 : _i >= 0; r = _ref <= 0 ? ++_i : --_i) {
    if (!selection.getRangeAt(r).collapsed) {
      lastRange = selection.getRangeAt(r);
      break;
    }
  }
  return lastRange;
};

get_offsets_and_remove = function($test_span) {
  var curr_elem, span_ht, total_offsetLeft, total_offsetTop;
  curr_elem = $test_span[0];
  total_offsetTop = 0;
  total_offsetLeft = 0;
  while (curr_elem !== null) {
    total_offsetTop += curr_elem.offsetTop;
    total_offsetLeft += curr_elem.offsetLeft;
    curr_elem = curr_elem.offsetParent;
  }
  span_ht = $test_span.height();
  $test_span.remove();
  return [total_offsetTop, total_offsetLeft, span_ht];
};

get_selection_offsets = function(selection) {
  var $test_span, lastRange, newRange;
  $test_span = $('<span class="smarterwiki-popup-bubble-test-span" style="display:inline;">x</span>');
  lastRange = getLastRange(selection);
  newRange = document.createRange();
  newRange.setStart(lastRange.endContainer, lastRange.endOffset);
  newRange.insertNode($test_span[0]);
  return get_offsets_and_remove($test_span);
};

fixPos = function(sel, e) {
  var fix, m_left, offsetLeft, offsetTop, offsets;
  offsets = get_selection_offsets(sel);
  offsetTop = offsets[0];
  offsetLeft = offsets[1];
  if (e != null) {
    if (offsetLeft < e.pageX - 100) {
      offsetLeft = e.pageX;
    }
    if (offsetTop < e.pageY - 100) {
      offsetLeft = e.pageY - 8;
    }
  } else {
    $('#showupbody').css('margin-left', '70px');
  }
  if (GetOpt('#Dis_st')) {
    offsetTop = offsetTop - 2 - $('#ShowUpBox').height();
    if ((offsetTop - document.documentElement.scrollTop) < 40) {
      offsetTop = document.documentElement.scrollTop + 40;
    }
  } else {
    offsetTop += 1.1 * offsets[2];
  }
  m_left = $('#ShowUpBox').width();
  fix = 0;
  if (offsetLeft - m_left < 4) {
    fix = 4 - offsetLeft + m_left;
  }
  $('#ShowUpBox').css("top", offsetTop + "px").css("left", (offsetLeft - m_left + fix) + "px");
  return $('#popuptip').css('margin-left', m_left - 20 - fix);
};

MouseIn = 0;

bTrans = 0;

$(document).mousedown(function(event) {
  if (bTrans === 1) {
    $('#ShowUpBox').remove();
    Init();
  }
  return $('#ShowUpBox').hide();
});

Inter = void 0;

TimeOutHide = function() {
  if (MouseIn === 0 && GetOpt("#Fade_st") && !bTrans) {
    return $('#ShowUpBox').fadeOut(600);
  }
};

Init = function() {
  var $DivBox;
  $DivBox = $('<span id="ShowUpBox"><span id="showupbody"><span id="popupwapper"></span><span id=Gspan></span></span></span>');
  $('body').append($DivBox);
  $DivBox.hide();
  $DivBox[0].style.cssText = "width:auto;height:auto;position:absolute;z-index:10240;display:inline;line-height:0;vertical-align:baseline;";
  $('#showupbody')[0].style.cssText = "all: unset;display: block;border:solid 2px rgb(144,144,144);border-radius:1px; background:-moz-linear-gradient(top, rgb(252, 252, 252) 0%, rgb(245, 245, 245) 33%, rgb(245, 245, 245) 100%);background:-webkit-linear-gradient(top, rgb(252, 252, 252), rgb(245, 245, 245));max-width: 750px !important;min-height: 20px;max-height: 350px;min-width: 20px;overflow:auto;";
  $('#showupbody')[0].style.cssText = "all: unset;display: block;border:solid 2px rgb(144,144,144);border-radius:1px; background:-moz-linear-gradient(top, rgb(252, 252, 252) 0%, rgb(245, 245, 245) 33%, rgb(245, 245, 245) 100%);background:-webkit-linear-gradient(top, rgb(252, 252, 252), rgb(245, 245, 245));max-width: 750px !important;min-height: 10px;max-height: 350px;min-width: 10px;overflow:auto;";
  if (!GetOpt("#Round_st")) {
    $('#showupbody').css({
      "border-radius": "4px"
    });
  }
  $DivBox.on("mouseup", function(event) {
    event.stopPropagation();
    if (event.which === 3) {
      event.preventDefault();
      GM_setClipboard(document.defaultView.getSelection().toString());
      $('#ShowUpBox').remove();
      Init();
      return false;
    } else if (event.which === 2) {
      event.preventDefault();
      return GM_openInTab(document.defaultView.getSelection().toString());
    }
  });
  $DivBox.on("contextmenu", function(event) {
    event.stopPropagation();
    event.preventDefault();
    return false;
  });
  document.getElementById("ShowUpBox").oncontextmenu = function(event) {
    event.stopPropagation();
    event.preventDefault();
    return false;
  };
  $DivBox.on("mousedown", function(event) {
    return event.stopPropagation();
  });
  $DivBox.on("dblclick", function(event) {
    return event.stopPropagation();
  });
  $DivBox.on("click", function(event) {
    return event.stopPropagation();
  });
  $DivBox.hover(function() {
    $(this).fadeTo(150, 1);
    return MouseIn = 1;
  }, function() {
    if (!bTrans) {
      $(this).fadeTo(300, 0.7);
      clearTimeout(Inter);
      Inter = setTimeout(TimeOutHide, 5500);
    }
    return MouseIn = 0;
  });
  $('#popupwapper').css({
    "margin": "3px 2px 3.8px 2px",
    "display": "block",
    "line-height": "0"
  });
  $('#popupwapper').append("<a id=gtransicon href=\"javascript:void(0)\"><img id=gtrans src=\"" + ticon + "\"></img></a>").append("<a id=openurl href=\"\" target=\"_blank\"><img id=iconie src=\"" + ie + "\"></img></a>").append("<a id=sbaidu href=\"\" target=\"_blank\"><img src=\"" + baiduico + "\"></img></a>").append("<a id=sbing href=\"\" target=\"_blank\"><img src=\"" + bingicon + "\"></img></a>").append("<a id=sgoogle href=\"\" target=\"_blank\"><img id=gicon src=\"" + gicon + "\"></img></a>");
  $('#sgoogle, #sbing, #sbaidu, #openurl').on("click", function(event) {
    return $('#ShowUpBox').hide();
  });
  $('#gtrans').on("click", function(event) {
    event.preventDefault();
    $("#Gspan").empty().append("<div style='padding:5px;'><img src=" + pending + " /></div>").show();
    $('#popupwapper').hide();
    fixPos(document.defaultView.getSelection());
    return GM_xmlhttpRequest({
      method: 'POST',
      url: 'http://203.208.46.200/translate_a/t',
      data: "client=p&text=" + txt + "&langpair=auto|auto",
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      onload: function(responseDetails) {
        var Rst, Rtxt, line, means, usage, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
        Rtxt = JSON.parse(responseDetails.responseText);
        Rst = '<div style="padding:10px;font-size:13px;overflow:auto;">';
        _ref = Rtxt.sentences;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          line = _ref[_i];
          Rst += line.trans + '<br>';
        }
        Rst += '<ul style="font-size:13px;list-style-position:inside;">';
        if (Rtxt.dict != null) {
          _ref1 = Rtxt.dict;
          for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
            usage = _ref1[_j];
            Rst += "<li>" + usage.pos + " : ";
            _ref2 = usage.entry;
            for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
              means = _ref2[_k];
              if (means.score > 0.005 || means.score > usage.entry[0].score / 2) {
                Rst += means.word + ', ';
              }
            }
            Rst += '</li>';
          }
        }
        $('#Gspan').empty().append(Rst + '</ul></div>').show();
        fixPos(document.defaultView.getSelection());
        return bTrans = 1;
      }
    });
  });
  if (!GetOpt('#Open_st')) {
    $('#openurl').hide();
  }
  if (!GetOpt('#Baidu_st')) {
    $('#sbaidu').hide();
  }
  if (!GetOpt('#Bing_st')) {
    $('#sbing').hide();
  }
  if (!GetOpt('#Google_st')) {
    $('#sgoogle').hide();
  }
  if (GetOpt('#Tab_st')) {
    $DivBox.find('a').attr('target', '_blank');
  } else {
    $DivBox.find('a').attr('target', '_self');
  }
  if (GetOpt('#Dis_st')) {
    tip = tipup;
    $DivBox.append($('<span id=popuptip></span>'));
    $('#popuptip').css({
      'margin-top': '-2px',
      'margin-bottom': '0px'
    });
  } else {
    tip = tipdown;
    $DivBox.prepend($('<span id=popuptip></span>'));
    $('#popuptip').css({
      'margin-top': '0px',
      'margin-bottom': '-2px'
    });
  }
  $('#popuptip').css({
    'background': 'url(' + tip + ') 0px 0px no-repeat transparent',
    'display': 'inline-block',
    'clear': 'both',
    'height': '9px',
    'width': '9px'
  });
  $('#Gspan').empty().css({
    "line-height": "normal",
    "width": "auto",
    "font-size": "16px",
    "padding": "25px!important",
    "overflow": "auto"
  }).hide();
  $('#ShowUpBox img').css({
    "margin": "0px 2px 0px 2px",
    "height": "20px",
    "width": "20px",
    "border-radius": "1px",
    "padding": "0px",
    "display": "inline-block",
    "-moz-transition-duration": "0.1s"
  });
  $('#ShowUpBox img').hover(function() {
    return $(this).css({
      "margin": "-1px 1px -1px 1px",
      "height": "22px",
      "width": "22px"
    });
  }, function() {
    return $(this).css({
      "margin": "0px 2px 0px 2px",
      "height": "20px",
      "width": "20px"
    });
  });
  return $DivBox.hide();
};

document.onmouseup = function(event) {
  if (event.which !== 1) {
    return;
  }
  if ($('#Ctrl_st').data('val') && !event.ctrlKey) {
    return;
  }
  window.lxe = event;
  return setTimeout(function() {
    return ShowBar(window.lxe);
  }, 50);
};

ShowBar = function(event) {
  var UrlText, sel, seltxt;
  sel = document.defaultView.getSelection();
  seltxt = sel.toString();
  if (seltxt === '' || InTextBox(sel)) {
    $('#ShowUpBox').hide();
    return;
  }
  if (GetOpt("#Copy_st")) {
    GM_setClipboard(seltxt);
  }
  txt = encodeURIComponent(seltxt);
  $('#Gspan').empty().hide();
  fixPos(sel, event);
  $('#sbaidu').attr('href', "http://www.baidu.com/s?wd=" + txt);
  $('#sbing').attr('href', "https://www.google.com/search?ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:zh-CN:unofficial&client=firefox-nightly&channel=rcs&q=" + txt);
  $('#sgoogle').attr('href', "https://translate.google.com/?langpair=auto|zh-CN&text=" + txt);
  UrlText = seltxt;
  if (UrlText.indexOf('http') === -1) {
    UrlText = 'http://' + UrlText;
  }
  MouseIn = 0;
  bTrans = 0;
  clearTimeout(Inter);
  Inter = setTimeout(TimeOutHide, 4000);
  $('#openurl').attr('href', UrlText);
  return $('#ShowUpBox').css('opacity', 0.9).fadeIn(150);
};

OpenSet = function() {
  return $('#popup_setting').show().css('top', '110px');
};

GetOpt = function(id) {
  return $(id).data('val');
};

SetOpt = function(id) {
  var dom, val;
  dom = $("#" + id);
  val = GM_getValue(id);
  if (!val) {
    dom.addClass('close');
  }
  dom.data('val', val);
  return dom.click(function() {
    $(this).toggleClass('close');
    if ($(this).data('val')) {
      return $(this).data('val', 0);
    } else {
      return $(this).data('val', 1);
    }
  });
};

SettingWin = function() {
  var SaveOpt, item, _i, _len, _ref;
  GM_addStyle('#popup_setting {all: unset;display:none; transition:0.6s ease top; top:-200%; text-align: justify;position:fixed;left:-moz-calc(50% - 310px);left:-webkit-calc(50% - 310px);width:600px;background:#FFF;box-shadow:0 0 5px #222;padding:20px 10px 50px 20px;z-index:102400;} #rol1,#rol2,#rol3,#rol4,#rol5{text-align: justify;} #popup_save{display:inline-block;position:absolute;right:15px;bottom:10px;} .setting_btn_inside{font-size:16px;padding:4px;-moz-user-select:none;cursor:default;}.setting_btn_inside:hover{background:#DDD;}.setting_btn_inside:active{box-shadow:0 0 3px #999 inset;}');
  GM_addStyle('.setting_sp_btn{min-width:120px;height:18px;font-size:12px;padding:4px;-moz-user-select:none;cursor:default;position:relative;margin:5px;margin-right:60px;display:inline-block;} .setting_sp_btn.close{background:#DDD;border:none;} .setting_sp_btn::before{position:absolute;right:-26px;top:0;content:" ";width:26px;height:26px;background:#6B4;transition:0.3s;} .setting_sp_btn.close::before{background:#C54;} .setting_sp_btn:hover{background:#DDD;} .setting_sp_btn:active{box-shadow:0 0 3px #999 inset;}');
  $("body").append('<div id="popup_setting"> <div style="font-size:16px;">PopUp设置:请选择需要显示的项目<br><br> </div> <div id="rol1"> </div> <div id="rol2"> </div> <div id="rol3"> </div> <div id="rol4"> </div> <div id = "btnarea"> <div style="font-size:12px;bottom:13px;position:absolute;left:20px;color:red;">请在Greasemonkey的"用户脚本命令"菜单的"Popup Search设置"下打开此选项</div> <div id="popup_save" class="setting_btn_inside" style="display:inline-block;">Save</div> <div id="popup_close" class="setting_btn_inside" style="display:inline-block;position:absolute;right:85px;bottom:10px;">Close</div> </div></div>');
  $("#rol1").append('<div id="Google_st">Google搜索</div> <div id="Bing_st">Bing搜索</div> <div id="Baidu_st">Baidu搜索</div>');
  $("#rol2").append('<div id="Open_st">选中视作链接打开按钮</div> <div id="Fade_st">超时自动隐藏</div> <div id="Dis_st">显示于文字上方</div>');
  $("#rol3").append('<div id="Tab_st"">新标签页打开</div> <div id="Copy_st">选中自动复制</div>  <div id="Ctrl_st">仅按下Ctrl时显示</div>');
  $("#rol4").append('<div id="Round_st"">弹出框直角风格</div>');
  $("#rol1 > div, #rol2 > div, #rol3 > div, #rol4 > div").addClass("setting_sp_btn");
  $("#popup_close").click(function() {
    $("#popup_setting").fadeOut(400, function() {
      $("#popup_setting").remove();
      return SettingWin();
    });
  });
  SaveOpt = function(id) {
    var dom;
    dom = $("#" + id);
    return GM_setValue(id, dom.data('val'));
  };
  _ref = $("#popup_setting .setting_sp_btn");
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    item = _ref[_i];
    if (item != null) {
      SetOpt(item.id);
    }
  }
  return $("#popup_save").click(function() {
    var _j, _len1, _ref1;
    _ref1 = $("#popup_setting .setting_sp_btn");
    for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
      item = _ref1[_j];
      if (item != null) {
        SaveOpt(item.id);
      }
    }
    $("#popup_setting").fadeOut(400, function() {
      $("#popup_setting").remove();
      return SettingWin();
    });
    $('#ShowUpBox').remove();
    return Init();
  });
};

Load = function() {
  var UpdateAlert, popupmenu;
  UpdateAlert = GM_getValue("UpdateAlert", 0);
  if (UpdateAlert < 4) {
    GM_setValue("UpdateAlert", 4);
    GM_setValue("Open_st", GM_getValue("Open_st", 1));
    GM_setValue("Baidu_st", GM_getValue("Baidu_st", 1));
    GM_setValue("Bing_st", GM_getValue("Bing_st", 1));
    GM_setValue("Google_st", GM_getValue("Google_st", 1));
    GM_setValue("Fade_st", GM_getValue("Fade_st", 1));
    GM_setValue("Ctrl_st", GM_getValue("Ctrl_st", 0));
    GM_setValue("Dis_st", GM_getValue("Dis_st", 1));
    GM_setValue("Tab_st", GM_getValue("Tab_st", 1));
    GM_setValue("Copy_st", GM_getValue("Copy_st", 0));
    GM_setValue("Round_st", GM_getValue("Round_st", 1));
    SettingWin();
    OpenSet();
  } else {
    SettingWin();
  }
  Init();
  GM_registerMenuCommand("Popup Search设置", OpenSet, 'p');
  if (GM_getValue("PopupMenu", 0)) {
    popupmenu = document.body.appendChild(document.createElement("menu"));
    popupmenu.outerHTML = '<menu id="userscript-popup" type="context"><menuitem id="Popupset" label="Popup Search设置"></menuitem></menu>';
    document.querySelector("#Popupset").addEventListener("click", OpenSet, false);
    return document.body.addEventListener("contextmenu", (function() {
      return document.body.setAttribute("contextmenu", "userscript-popup");
    }), false);
  }
};

setTimeout(Load, 100);

